using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using Honest.MES.Contracts.Interfaces;
using Honest.MES.WPF.Constants;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation.Regions;

namespace Honest.MES.WPF.ViewModels
{
    public class MainWindowViewModel : BindableBase, IDisposable
    {
        private readonly IRegionManager _regionManager;
        private readonly IModuleDiscoveryService _moduleDiscoveryService;
        private readonly ILoggerService _loggerService;

        private string _title = "Honest MES";
        private WindowState _windowState = WindowState.Normal;

        public MainWindowViewModel(
            IRegionManager regionManager,
            IModuleDiscoveryService moduleDiscoveryService,
            ILoggerService loggerService)
        {
            _regionManager = regionManager;
            _moduleDiscoveryService = moduleDiscoveryService;
            _loggerService = loggerService;

            // 初始化命令
            ExitCommand = new DelegateCommand(OnExit);
            MinimizeCommand = new DelegateCommand(OnMinimize);
            MaximizeCommand = new DelegateCommand(OnMaximize);
            RestoreCommand = new DelegateCommand(OnRestore);

            _loggerService.Info("MainWindowViewModel 已初始化");

            // 订阅模块发现事件
            _moduleDiscoveryService.ModulesDiscovered += OnModulesDiscovered;

            // 初始发现模块
            _moduleDiscoveryService.DiscoverModules();
        }

        public string Title
        {
            get => _title;
            set => SetProperty(ref _title, value);
        }

        public WindowState WindowState
        {
            get => _windowState;
            set => SetProperty(ref _windowState, value);
        }

        public ICommand ExitCommand { get; }
        public ICommand MinimizeCommand { get; }
        public ICommand MaximizeCommand { get; }
        public ICommand RestoreCommand { get; }

        private void OnExit()
        {
            _loggerService.Info("应用程序退出");
            Application.Current.Shutdown();
        }

        private void OnMinimize()
        {
            WindowState = WindowState.Minimized;
        }

        private void OnMaximize()
        {
            WindowState = WindowState.Maximized;
        }

        private void OnRestore()
        {
            WindowState = WindowState.Normal;
        }



        private void OnModulesDiscovered(object sender, Honest.MES.Contracts.Events.ModulesDiscoveredEventArgs e)
        {
            _loggerService.Info($"发现 {e.Modules.Count()} 个模块");

            // 导航到默认视图
            _regionManager.RequestNavigate(RegionNames.MainRegion, "DefaultView");
        }

        public void Dispose()
        {
            // 取消事件订阅
            _moduleDiscoveryService.ModulesDiscovered -= OnModulesDiscovered;

            _loggerService.Info("MainWindowViewModel 已释放");
        }
    }
}